import React from 'react'

// 状态的类型
type Porps = {
  onAddTodo(text: string): void
}

// 状态类型
type State = {
  text: string
}

class TodoAdd extends React.Component<Porps, State> {
  state: State = {
    text: ''
  }

  onchange = (e:React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      text: e.target.value
    })
  }

  onAdd = (e: React.KeyboardEvent<HTMLInputElement>) => {
    const { text } = this.state
    if(text && e.keyCode === 13) {
      this.props.onAddTodo(text)
      this.setState({
        text: ''
      })
    }
  }

  render() {
    return (
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          placeholder="What needs to be done?"
          autoFocus
          value={this.state.text}
          onChange={this.onchange}
          onKeyDown={this.onAdd}
        />
      </header>
    )
  }
}

export default TodoAdd
